
var I18N = { 
  'en': {
     "模拟账户": "Demo Account"
  }, 
  'ja': {
     "模拟账户": "デモアカウント"
  },  
  'ko': {
     "模拟账户": "데모 계정"
  },  
  'tc': {
     "模拟账户": "模擬賬戶"
  }, 
};
var language = weex.config.language;
var msg = I18N[language];
if(!msg){ msg = {} }
var T = function(text){ return msg[text] || text };

const WeexFunction = weex.requireModule("WeexFunction");
import API from "@/_js/api";
var kDefaultkey = 'DEFAULT_API';
export default {
  
  /** 获取默认API
   * 
   * @param {function} success 成功回调
   */
  getDefaultApi(success=(api, counterCoin, baseCoin)=>{}){

    var counterCoin = 'BTC';
    var baseCoin = 'USDT';
    var exchange = API.getExchanges('Huobi');
    var api = this.getMimicApi(exchange);  //默认API-模拟
    API.getApi((apis)=>{

      //1、未录入API使用：“默认API-模拟”
      if (apis.length == 0) {
        success(api, counterCoin, baseCoin);
        return;
      }
      
      /*默认API-实盘*/
      api = apis[0];
      WeexFunction.getConfig(kDefaultkey, (e)=>{
        
        //2、“缓存API-实盘”不存在使用：“默认API-实盘”
        if (e.length == 0) {
          this.initApiFee(api);
          this.setDefaultApi(api.apiId, counterCoin, baseCoin);
          success(api, counterCoin, baseCoin);
          return;
        }
        
        //3、查找“缓存API-实盘”，存在使用。
        e = JSON.parse(e);
        for (let index = 0; index < apis.length; index++) {
          var apix = apis[index];
          if (apix.apiId == e.apiId) {
            api = apix
            counterCoin = e.counterCoin;
            baseCoin = e.baseCoin;
            break;
          }
        }

        this.initApiFee(api);
        this.setDefaultApi(api.apiId, counterCoin, baseCoin);
        success(api, counterCoin, baseCoin);
      });
    });
  },

  /** 获取模拟盘API
   * 
   * @param {JSON} e 交易所对象
   */
  getMimicApi(e){    

    var api = {'exchangeName':e.exchangeName,
              'exchangeId':e.exchangeId,
              'apiName':e.exchangeName + ' - ' + T('模拟账户'),
              'tradeFee':e.tradeFee,
              'apiId':'',
              'accountAssets':[]};
    return api;
  },

  /** 初始化API手续费
   * 
   * @param {JSON}} api API对象
   */
  initApiFee(api){
      
    //1、手续费存在
    if (api.tradeFee != null) {
      api.tradeFee = api.tradeFee +'';
    } 

    //2、手续费不存在
    else {
      api.tradeFee = API.getApiFee(api.exchangeName);
      API.modifyApiFee(api.apiId, api.tradeFee);
    }
  },
  
  //设置默认Api
  setDefaultApi(apiId, counterCoin, baseCoin) {

    var dict = {'apiId':apiId,
                'counterCoin':counterCoin, 
                'baseCoin':baseCoin};
    var str = JSON.stringify(dict);
    WeexFunction.setConfig(this.apiTag, str,()=>{});
  },
}
